package UDP.Demo2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceiver {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket，监听端口9876
            DatagramSocket socket = new DatagramSocket(9876);
            System.out.println("UDP广播接收端已启动，等待广播消息...");

            while (true) {
                // 接收广播数据包
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);

                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("收到广播消息: " + message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}